<?php
header("content-type:text/html;charset=utf-8");
// 按行读取txt文件
function txt2Array($file_path)
{
    return file($file_path, FILE_IGNORE_NEW_LINES);
}

class Operation
{
    public static $type = "";
    private static $typeArray = [
        "填空题" => ["name" => "填空题", "state" => 1],
        "简答题" => ["name" => "简答题", "state" => 1],
        "计算题" => ["name" => "计算题", "state" => 1],
        "单选题" => ["name" => "单选题", "state" => 1],
        "单项选择题" => ["name" => "单选题", "state" => 1],
        "多项选择题" => ["name" => "多选题", "state" => 0],
        "名词解释" => ["name" => "名词解释", "state" => 0],
        "论述题" => ["name" => "论述题", "state" => 0],
    ];

    static function setStemType($s): string
    {
        foreach (Operation::$typeArray as $k => $v) {
            if (substr_count($s, $k)) {
                if ($v["state"]) {
                    self::$type = $v["name"];
                } else {
                    self::$type = "";
                }
                return true;
            }
        }
        return false;
    }

    static function getScore($item)
    {
        $tmp = explode("每", $item);
        preg_match("/[0-9]{1,2}/", $tmp[1], $scoreArr);
        return $scoreArr[0];
    }

    static function idxOff($t)
    {
        $len = 0;
        if (preg_match("/^[0-9]{1,2}/", $t, $res)) {
            $len = strlen($res[0]);
        }
        if (preg_match("/^[0-9]{1,2}[．]/", $t, $res)) {
            $len += 3;
        }
        if (preg_match("/^[0-9]{1,2}[.]/", $t, $res)) {
            $len += 1;
        }

        return substr($t, $len);
    }

    static function addUnderLine($stem)
    {
        $stem = str_replace("．	", "．", $stem);
        print_r($stem);
        $stem = str_replace("  ", "__", $stem);
        return str_replace("　", "_", $stem);
    }

    static function splitStemOptions($stem)
    {

        $stem = str_replace("A.", "\nA.", $stem);
        $stem = str_replace("A、", "\nA.", $stem);
        $stem = str_replace("A．", "\nA.", $stem);
        $rs = explode("\n", $stem);

        $options = $rs[1];
        $options = str_replace("B.", "\nB.", $options);
        $options = str_replace("C.", "\nC.", $options);
        $options = str_replace("D.", "\nD.", $options);
        $options = str_replace("E.", "\nE.", $options);
        $options = str_replace("F.", "\nF.", $options);
        $options = str_replace("G.", "\nG.", $options);

        $options = str_replace("B、", "\nB.", $options);
        $options = str_replace("C、", "\nC.", $options);
        $options = str_replace("D、", "\nD.", $options);
        $options = str_replace("E、", "\nE.", $options);
        $options = str_replace("F、", "\nF.", $options);
        $options = str_replace("G、", "\nG.", $options);

        $options = str_replace("B．", "\nB.", $options);
        $options = str_replace("C．", "\nC.", $options);
        $options = str_replace("D．", "\nD.", $options);
        $options = str_replace("E．", "\nE.", $options);
        $options = str_replace("F．", "\nF.", $options);
        $options = str_replace("G．", "\nG.", $options);

        $rs[1] = $options;
        return $rs;
    }


    static function splitOptions($option)
    {
        $option = str_replace(" ", "", $option);
        $option = str_replace("；", "", $option);
        $option = str_replace("。", "", $option);

        $option = str_replace("A.", "", $option);
        $option = str_replace("B.", ";", $option);
        $option = str_replace("C.", ";", $option);
        $option = str_replace("D.", ";", $option);
        $option = str_replace("E.", ";", $option);
        $option = str_replace("F.", ";", $option);
        $option = str_replace("G.", ";", $option);

        $option = str_replace("A、", "", $option);
        $option = str_replace("B、", ";", $option);
        $option = str_replace("C、", ";", $option);
        $option = str_replace("D、", ";", $option);
        $option = str_replace("E、", ";", $option);
        $option = str_replace("F、", ";", $option);
        $option = str_replace("G、", ";", $option);

        $option = str_replace("A．", "", $option);
        $option = str_replace("B．", ";", $option);
        $option = str_replace("C．", ";", $option);
        $option = str_replace("D．", ";", $option);
        $option = str_replace("E. ", ";", $option);
        $option = str_replace("E．", ";", $option);
        $option = str_replace("F．", ";", $option);
        $option = str_replace("G．", ";", $option);


        $option = str_replace("（a）", "", $option);
        $option = str_replace("（b）", ";", $option);
        $option = str_replace("（c）", ";", $option);
        $option = str_replace("（d）", ";", $option);
        $option = str_replace("（e）", ";", $option);
        $option = str_replace("（f）", ";", $option);
        $option = str_replace("（g）", ";", $option);


        $option = str_replace("（A）", "", $option);
        $option = str_replace("（B）", ";", $option);
        $option = str_replace("（C）", ";", $option);
        $option = str_replace("（D）", ";", $option);
        $option = str_replace("（E）", ";", $option);


        $option = str_replace("A:", "", $option);
        $option = str_replace("B:", ";", $option);
        $option = str_replace("C:", ";", $option);
        $option = str_replace("D:", ";", $option);
        $option = str_replace("E:", ";", $option);

        preg_match_all("/[A-E]{1,5}/", $option, $oas);
        if (!empty($oas)) {
            if ((count($oas[0]) == 4 && implode("", $oas[0]) == 'ABCD') ||
                (count($oas[0]) == 5 && implode("", $oas[0]) == 'ABCDE')
            ) {
                $option = str_replace(["A"], "", $option);
                $option = str_replace(["B", "C", "D", "E"], ";", $option);
            }
        }


        return $option;
    }

}


//难易程度
function setLevel($stem, $question): void
{
    if (preg_match("/(\().*[易难].*(\))$/", $stem, $levelArr)) {
        $levelStr = $levelArr[0];
    }
    if (!empty($levelStr)) {
        $stem = str_replace($levelStr, "", $stem);
    }
    $levelArray = ["偏易" => 2, "偏难" => 4, "易" => 1, "难" => 5];
    if (!empty($levelStr)) {
        foreach ($levelArray as $key => $val) {
            if (strpos($levelStr, "$key") != false) {
                $question->setLevel($val);;
                break;
            }
        }
    }
}

//识别题干内答案 括号里，题干最后 题干最前
function getAnswerFromStem($answerStr): string
{
    $answerStr = str_replace("　", "", $answerStr);
    $answerStr = str_replace(" ", "", $answerStr);
    $_rr = ["√", "×"];
    $_ab = ["A", "B"];
    $answerStr = str_replace($_rr, $_ab, $answerStr);
    $_rr = ['√', '╳'];
    $answerStr = str_replace($_rr, $_ab, $answerStr);
    preg_match("/(\()[A-Ga-g]{1,5}(\))/", $answerStr, $anwers);
    if (!empty($anwers)) {
        preg_match("/[A-Ga-g]{1,5}/", $anwers[0], $answersArr);
        return $answersArr[0];
    }
    preg_match("/(（)[A-Ga-g]{1,5}(）)/", $answerStr, $anwers);
    if (!empty($anwers)) {
        preg_match("/[A-Ga-g]{1,5}/", $anwers[0], $answersArr);
        return $answersArr[0];
    }
    preg_match("/[A-Ga-g]{1,5}$/", $answerStr, $anwers);
    if (!empty($anwers)) {
        preg_match("/[A-Ga-g]{1,5}/", $anwers[0], $answersArr);
        return $answersArr[0];
    }
    return "";
}

//选择题。题干，难易
function createQuestion($item, $type, $score, $questionMap): array
{
    $stem = $item;
    $stem = str_replace("　", "", $stem);
    $stem = str_replace(" ", "", $stem);
    $_rr = ["√", "×"];
    $_ab = ["A", "B"];
    $stem = str_replace($_rr, $_ab, $stem);
    $_rr = ['√', '╳'];
    $stem = str_replace($_rr, $_ab, $stem);
    if (preg_match("/^(（)?[0-9]{1,3}(）)?/", $stem, $questionNOArr) ||
        preg_match("/^(（)[A-Ea-e](）)[0-9]{1,2}/", $stem, $questionNOArr)
    ) {

        $question = new QuestionDO();
        $question->setAnswer(getAnswerFromStem($item));
        $stem = preg_replace("/^(（)[A-Ea-e](）)[0-9]{1,2}(\.)?/", "", $stem);
        $stem = preg_replace("/^(（)?[0-9]{1,3}(）)?(、)?(．)?(\.)?/", "", $stem);
        $stem = preg_replace("/(\().*(\))/", "{block}", $stem);
        $stem = preg_replace("/(（).*(）)/", "{block}", $stem);
        $stem = preg_replace("/[A-Ea-e]{1,5}$/", "", $stem);

        $stem = str_replace("{block}", "（    ）", $stem);
        $question->setStem($stem);
        $question->setType($type);
        $question->setScore($score);

        $questionIdx = $questionNOArr[0];
        if (preg_match("/[0-9]{1,3}/", $questionNOArr[0], $questionNOArr1)) {
            $questionIdx = $questionNOArr1[0];
            if (array_key_exists($questionIdx, $questionMap)) {
                $questionIdx = $type . $questionIdx;
            }
        }
        $questionMap[$questionIdx] = $question;
    }

    return $questionMap;
}

//选择题。选项
function setOperation($operaStr, $question): void
{
    $_dbc = ['Ａ', 'Ｂ', 'Ｃ', 'Ｄ', 'Ｅ', 'Ｆ', 'Ｇ'];
    $_sbc_ = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
    $operaStr = str_replace($_dbc, $_sbc_, $operaStr);
    $operaStr = str_replace("　", "", $operaStr);
    if (strpos($operaStr, "A") === 0
        || strpos($operaStr, "B") === 0
        || strpos($operaStr, "C") === 0
        || strpos($operaStr, "D") === 0
        || strpos($operaStr, "E") === 0
    ) {
        if (empty($question->getOperation())) {
            $question->setOperation($operaStr);
        } else {
            $question->setOperation($question->getOperation() . $operaStr);
        }
        $question->setOperation(Operation::splitOptions($question->getOperation()));
    }
}

//选择题    答案
function setAnswerArray($answerStrAll, $questionMap): void
{
    if (empty($answerStrAll)) {
        return;
    }
    $_dbc = ['Ａ', 'Ｂ', 'Ｃ', 'Ｄ', 'Ｅ', 'Ｆ', 'Ｇ'];
    $_sbc = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
    $nonStr = [" ", "．", "（", "）"];
    $answerStrAll = str_replace($nonStr, "", $answerStrAll);
    $answerStrAll = str_replace($_dbc, $_sbc, $answerStrAll);
    $_rr = ["√", "×"];
    $_ab = ["A", "B"];
    $answerStrAll = str_replace($_rr, $_ab, $answerStrAll);
    $_rr = ['√', '╳'];
    $answerStrAll = str_replace($_rr, $_ab, $answerStrAll);

    preg_match_all("/[0-9]{1,5}/", $answerStrAll, $numbersArr);
    preg_match_all("/[A-Ga-g]{1,5}/", $answerStrAll, $answersArr);
    $answerMap = array_combine($numbersArr[0], $answersArr[0]);
    foreach ($questionMap as $number => $question) {
        if (!empty($question->getStem()) && key_exists($number, $answerMap)) {

            $question->setAnswer($answerMap[$number]);
        }
        else{
            print_r($answerMap[$number]) ;
        }
    }
}

//读取 分数
function getScore($item)
{
    $score = null;
    preg_match("/(每)(小)?(题)\d(分)/", $item, $scores);
    if (!empty($scores)) {
        $score = str_replace(["每", "小", "题", "分"], "", $scores[0]);
    }
    return $score;
}